﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ButsaScraperLib;
using ForecastPair = ButsaLib.Models.ForecastPair;

namespace ButsaForecast.Dialogs
{
	/// <summary>
	/// Interaction logic for LoadResultsDialog.xaml
	/// </summary>
	public partial class LoadResultsDialog
	{
		private readonly List<ForecastPair> _forecastPairs;
 
		public LoadResultsDialog(List<ForecastPair> forecastPairs)
		{
			InitializeComponent();

			_forecastPairs = forecastPairs;

			Thread thread = new Thread(ExecuteDialog) { IsBackground = true };
			thread.Start();
		}

		private void ExecuteDialog()
		{
			Parallel.ForEach(_forecastPairs, new ParallelOptions { MaxDegreeOfParallelism = 1 }, currentPair =>
			{
				Score score = ButsaManager.Instance.GetMatchResultForTeams(currentPair.HomeTeamShot.TeamId.ToString(),
					currentPair.GuestTeamShot.TeamId.ToString());

				currentPair.GuestTeamGoals = score.GuestTeamGoals;
				currentPair.HomeTeamGoals = score.HomeTeamGoals;

				LogMessage(String.Format("{0} - {1} {2}:{3}", currentPair.HomeTeamShot.TeamName, currentPair.GuestTeamShot.TeamName,
					currentPair.HomeTeamGoals, currentPair.GuestTeamGoals));
			});
			Dispatcher.Invoke(new Action(() => { DialogResult = true; }));
			
		}

		private void LogMessage(string message)
		{
			if (LogTextBox.Dispatcher.CheckAccess())
			{
				LogTextBox.Text = message + "\r\n" + LogTextBox.Text;
			}
			else
			{
				LogTextBox.Dispatcher.Invoke(new Action(() => LogMessage(message)), new object[] { });
			}
		}
	}
}
